package com.haidao.admin.component.service.impl;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.core.io.resource.MultiResource;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import com.haidao.admin.component.service.UploadFileService;
import com.haidao.admin.core.result.Err;
import com.haidao.admin.core.result.Resp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;

@Service
@Slf4j
public class UploadFileServiceImpl implements UploadFileService {
    @Value("${report.baseUrl}")
    private String baseUrl;

    @Value("${report.cmcId}")
    private String cmcId;

    @Override
    public Resp<String> upload(MultipartFile file) throws IOException {
        MultiResource multiResource = new MultiResource(new InputStreamResource(file.getInputStream(), file.getOriginalFilename()));
        String uri = "/mpscmc/v1/fs/upload";
        String url = baseUrl + uri;
        HashMap<String, String> headers = new HashMap<>();
        headers.put("cmcId", cmcId);
        headers.put("Content-Type", "multipart/form-data");
        String body = HttpRequest.post(url)
                .addHeaders(headers)
                .form("file", multiResource).execute().body();
        log.error("图片上传结果:"+body);
        JSONObject bodyJson = new JSONObject(body);
        if (bodyJson.containsKey("code") && bodyJson.getInt("code") == 0) {
            return Resp.ok(bodyJson.getStr("fileId"));
        }
        log.error("上传失败: {}", body);
        return Resp.fail(Err.ERR, "上传失败");
    }

}
